package models

import (
	"errors"
	"gorm.io/gorm"
	"strings"
	"time"
)

// FileGroup 文件分组
type FileGroup struct {
	Id        uint           `json:"id"`
	Name      string         `json:"name"`
	ParentId  uint           `json:"parent_id"`
	Order     uint           `json:"order"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `json:"-"`
	Children  []FileGroup    `json:"children" gorm:"-"`
}

// @title 数据校验
func (f *FileGroup) validate() error {
	if f.Name == "" {
		return errors.New("分组名称不能为空")
	}

	return nil
}

// @title 添加
func (f *FileGroup) Store() error {
	err := f.validate()

	if err != nil {
		return err
	}

	f.Id = 0

	return Db.Create(f).Error
}

// @title 获取树状列表
func (f *FileGroup) TreeList() ([]map[string]interface{}, error) {
	var list []FileGroup

	err := Db.Order("`order`").Find(&list).Error

	if err != nil {
		return nil, err
	}

	data := DateTimeFormatList(list, []string{"created_at", "updated_at"})

	return treeHandler(data, 0), nil
}

// @title 获取单条信息
func (f *FileGroup) GetOne(id string) FileGroup {
	var data FileGroup

	Db.Model(f).Where("id = ?", id).First(&data)

	return data
}

// @title 更新
func (f *FileGroup) Update() error {
	err := f.validate()

	if err != nil {
		return err
	}

	return Db.Save(f).Error
}

// @title 删除
func (a *FileGroup) Delete() error {
	var sub []FileGroup

	Db.Model(a).Where("parent_id = ?", a.Id).Find(&sub)

	if len(sub) > 0 {
		for _, item := range sub {
			item.Delete()
		}
	}

	return Db.Delete(a).Error
}

// @title 删除多个
func (a *FileGroup) Deletes(ids string) error {
	var list []FileGroup

	Db.Model(a).Where("id in (?)", strings.Split(ids, ",")).Find(&list)

	if len(list) > 0 {
		for _, item := range list {
			item.Delete()
		}
	}

	return nil
}
